<?php

namespace App\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class MiniappService
{
    public static function jscode($appid, $secret, $js_code, $grant_type = 'authorization_code')
    {
        $wxUrl = "https://api.weixin.qq.com/sns/jscode2session";
        $params = compact('appid', 'secret', 'js_code', 'grant_type');
        try {
            $query = http_build_query($params);
            $url = $wxUrl . '?' . $query;

            $client = new Client(['verify' => false]);
            $response = $client->get($url);

            $result = json_decode($response->getBody(), true);
            logs()->error('微信登录接口请求成功：' . json_encode($result));
            if (isset($result['errcode']) && $result['errcode'] !== 0) {
                return [$result['errcode'], $result['errmsg']];
            }
        } catch (GuzzleException $e) {
            logs()->error('微信登录接口请求失败：' . $e->getMessage());
            return [503, '微信登录接口请求失败'];
        }
        return [200, $result];
    }
}
